<template>
    <div style="padding:30px;">
        <el-alert :closable="false" title="">
            <transition name="fade-transform" mode="out-in">
                <template>
                    <div class="sort-root">
                        <div class="sort-left">
                            <el-input placeholder="输入关键字进行过滤" v-model="filterText" :blur="inputChanged">
                            </el-input>
                            <div class="treeDiv">
                                <el-tree class="filter-tree" :data="deptData" :props="defaultProps"
                                    :filter-node-method="filterNode" @node-click="handleNodeClick" ref="tree"></el-tree>
                            </div>
                        </div>
                        <div class="sort-right">
                            <div class="right-header" v-if="roomOptions && roomOptions.length > 0">
                                <el-select v-model="roomValue" filterable placeholder="请选择" @change="changedRoomValue">
                                    <el-option v-for="item in roomOptions" :key="item.roomId" :label="item.roomName"
                                        :value="item.roomId">
                                    </el-option>
                                </el-select>

                                <el-button type="primary" @click="addLine">添加行</el-button>
                                <el-button type="primary" @click="saveAll">保存</el-button>
                            </div>
                            <div class="right-main">
                                <el-table :data="sortList" style="width: 100%">
                                    <el-table-column label="时间(时:分)">
                                        <template slot-scope="scope">
                                            <div @click="timeDialogFun(scope.row)">{{ scope.row.begintime }}-{{
                                                    scope.row.endtime
                                            }}</div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-for="(week, index) in weekList" :key="index" :label="week">
                                        <template slot-scope="scope">
                                            <span @click="clickChangedRoom(scope.row, week)">{{ getRoomByWeek(week,
                                                    scope.row)
                                            }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column fixed="right" label="操作" width="150">
                                        <template slot-scope="scope">
                                            <el-button type="primary" @click="onDelete(scope.row)">删除</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>

                            </div>
                            <!-- <div class="right-footer">Footer</div> -->
                        </div>

                        <el-dialog title="提示" :visible.sync="timeDialog" width="40%" center>
                            <div>
                                <el-time-picker is-range v-model="curTime" range-separator="至" start-placeholder="开始时间"
                                    end-placeholder="结束时间" placeholder="选择时间范围">
                                </el-time-picker>
                            </div>
                            <span slot="footer" class="dialog-footer">
                                <el-button @click="timeDialog = false">取 消</el-button>
                                <el-button type="primary" @click="clickOkTimeDialog()">确 定</el-button>
                            </span>
                        </el-dialog>
                        <el-dialog title="提示" :visible.sync="roomDialog" width="40%" center>
                            <div>
                                <el-select v-model="currRoomId" filterable placeholder="请选择">
                                    <el-option v-for="item in roomOptions" :key="item.roomId" :label="item.roomName"
                                        :value="item.roomId">
                                    </el-option>
                                </el-select>
                            </div>
                            <span slot="footer" class="dialog-footer">
                                <el-button @click="roomDialog = false">取 消</el-button>
                                <el-button type="primary" @click="clickOkRoomDialog()">确 定</el-button>
                            </span>
                        </el-dialog>
                    </div>
                </template>
            </transition>
        </el-alert>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { IDeptModel, IRoomModel, IRoomSortModel, ISortModel, IWeekModel } from '@/api/types';
import { DeptsModule } from '@/store/modules/dept';
import { RoomSortModule } from '@/store/modules/room_sort';


@Component({
    name: 'Sort',
    components: {
    }
})
export default class extends Vue {
    public allList: Array<IDeptModel> = []
    public list: Array<IDeptModel> = []
    public listLoading: boolean = false
    scope: any;
    $refs: any;
    public optType: string = ""
    public isShow = false;
    public iHeight = window.innerHeight - 300;

    public currentPage: number = 1;
    public pageSize: number = 10;
    public totalSize: number = 0;

    public deptData = []
    public filterText = "";

    public roomOptions: Array<IRoomModel> = [];
    public roomValue = "";

    public weekList = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
    public sortList: Array<ISortModel> = [
    ];
    public roomSortList: Array<IRoomSortModel> = [];
    public curRoomSort: any = { startTimeValue: "", endTimeValue: "" };
    public curTime: any = {};

    public srcList: Array<IRoomSortModel> = [];
    public timeDialog: boolean = false;
    public roomDialog: boolean = false;
    public currRoom: any = {};
    public currRoomId: any = "";
    public currWeek: string = "";

    @Watch("filterText")
    public filterTextChanged(val: string, oldVal: string) {
        this.$refs.tree.filter(val);
    }

    public defaultProps = {
        children: 'children',
        label: 'deptName'
    }

    public filterNode(value: any, data: any) {
        if (!value) return true;
        return data.deptName.indexOf(value) !== -1;
    }

    public async handleNodeClick(v: any) {
        console.error(v);
        let info: any = await DeptsModule.getDeptRooms(v.dept.deptId);
        this.roomOptions = info.rooms;
    }

    public inputChanged() {
        this.$refs.tree.filter(this.filterText);
    }

    public addLine() {
        if (!this.roomValue) return;
        let list = [];
        let room = this.getRoomByName();
        let weeks = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
        for (let i = 0; i < 7; i++) {
            let mod: IRoomSortModel = {
                week: weeks[i],//`json:"week"          ` // 星期
                begintime: "00:00:00", //`json:"begintime"     ` // 开始时间
                endtime: "00:00:00", //`json:"endtime"       ` // 结束时间
                roomName: room ? room.roomName : "", //`json:"roomName"      ` // 诊室名称
                roomId: room ? room.roomId : "", //`json:"roomId"        ` // 诊室ID
                baseroomName: room ? room.roomName : "",  //`json:"baseroomName" ` // 基础诊室名称
                baseroomId: room ? room.roomId : "",//`json:"baseroomId"   ` // 基础诊室ID
            }
            list.push(mod);
        }
        //发送添加到数据库
        let result: Array<ISortModel> = [];
        //同一个开始时间和结束时间的就是一行数据
        for (let i = 0; i < list.length; i++) {
            let isHave: boolean = false;
            for (let j = 0; j < result.length; j++) {
                if (result[j].begintime == list[i].begintime && result[j].endtime == list[i].endtime) {
                    isHave = true;
                    let week: IWeekModel = {
                        sortId: 0,
                        roomId: list[i].roomId,
                        roomName: list[i].roomName,
                        weekName: list[i].week,
                    }
                    result[j].weeks.push(week);
                    break;
                }
            }
            if (!isHave) {
                let week: IWeekModel = {
                    sortId: 0,
                    roomId: list[i].roomId,
                    roomName: list[i].roomName,
                    weekName: list[i].week,
                }
                let sortMod: ISortModel = {
                    sortId: 0,
                    begintime: list[i].begintime,
                    endtime: list[i].endtime,
                    baseroomId: list[i].baseroomId,
                    baseroomName: list[i].baseroomName,
                    weeks: [
                        week
                    ]
                }
                result.push(sortMod);
            }
        }
        this.sortList.push(...result);
        //发送list 到数据库.判断如果有 00:00 - 00:00 就不用发送了,有一条数据没设置的
        let boo = this.roomSortList.some(value => {
            return value.begintime == "00:00:00" && value.endtime == "00:00:00" && value.baseroomId == this.roomValue
        });
        if (boo) {
            return
        }
    }

    public getRoomByWeek(week: string, row: any) {
        let roomName = "";
        let modList = this.sortList.filter(value => {
            return value.begintime == row.begintime && value.endtime == row.endtime;
        })
        if (modList && modList.length > 0) {
            for (let i = 0; i < modList[0].weeks.length; i++) {
                if (modList[0].weeks[i].weekName == week) {
                    roomName = modList[0].weeks[i].roomName;
                    break;
                }
            }
        }
        return roomName
    }

    public getRoomByName() {
        let arr = this.roomOptions.filter(value => {
            return value.roomId == this.roomValue
        });
        if (arr && arr.length > 0) {
            return arr[0]
        }
        return null;
    }

    public clickChangedRoom(row: any, week: string) {
        console.error(row);
        this.currRoom = row;
        this.roomDialog = true;
        this.currWeek = week;
    }

    public async changedRoomValue(value: any) {


        let resultList: any = await RoomSortModule.getRoomSorts(value)
        console.error(resultList);
        this.srcList = resultList;
        if (!resultList) {
            this.sortList = [];
        } else {
            this.updateShowList(resultList);
        }
    }

    public updateShowList(resultList: any) {
        //发送添加到数据库
        let result: Array<ISortModel> = [];
        //同一个开始时间和结束时间的就是一行数据
        for (let i = 0; i < resultList.length; i++) {
            let isHave: boolean = false;
            for (let j = 0; j < result.length; j++) {
                if (result[j].begintime == resultList[i].begintime && result[j].endtime == resultList[i].endtime) {
                    isHave = true;
                    let week: IWeekModel = {
                        sortId: resultList[i].sortId,
                        roomId: resultList[i].roomId,
                        roomName: resultList[i].roomName,
                        weekName: resultList[i].week,
                    }
                    result[j].weeks.push(week);
                    break;
                }
            }
            if (!isHave) {
                let week: IWeekModel = {
                    sortId: resultList[i].sortId,
                    roomId: resultList[i].roomId,
                    roomName: resultList[i].roomName,
                    weekName: resultList[i].week,
                }
                let sortMod: ISortModel = {
                    sortId: resultList[i].sortId,
                    begintime: resultList[i].begintime,
                    endtime: resultList[i].endtime,
                    baseroomId: resultList[i].roomId,
                    baseroomName: resultList[i].roomName,
                    weeks: [
                        week
                    ]
                }
                result.push(sortMod);
            }
        }
        console.error(result);
        this.sortList = result;
    }

    public clickOkRoomDialog() {
        let roomInfo: any = undefined;
        this.roomOptions.forEach(value => {
            if (value.roomId == this.currRoomId) {
                roomInfo = value;
            }
        })
        if (roomInfo) {
            this.currRoom.weeks.forEach((value: IWeekModel) => {
                if (value.weekName == this.currWeek) {
                    value.roomId = this.currRoomId;
                    value.roomName = roomInfo.roomName;
                }
            });
        }
        console.error(this.currRoom, this.currRoomId);
        this.roomDialog = false;
    }

    public timeDialogFun(row: any) {
        this.curRoomSort = row;
        this.timeDialog = true;
        console.error(row);
    }

    public clickOkTimeDialog() {
        console.error(this.curTime, this.curRoomSort);
        let t1 = (<Date>this.curTime[0]);
        if (!t1) return;
        console.error(t1.getHours() + ":" + t1.getMinutes());
        let t2 = (<Date>this.curTime[1]);
        let t1Hours = t1.getHours();
        let t1Minutes = t1.getMinutes();
        let t1Seconds = t1.getSeconds();
        this.curRoomSort.begintime = (t1Hours < 10 ? "0" + t1Hours : t1Hours) + ":" + (t1Minutes < 10 ? "0" + t1Minutes : t1Minutes)
            + ":" + (t1Seconds < 10 ? "0" + t1Seconds : t1Seconds);

        let t2Hours = t2.getHours();
        let t2Minutes = t2.getMinutes();
        let t2Seconds = t2.getSeconds();
        this.curRoomSort.endtime = (t2Hours < 10 ? "0" + t2Hours : t2Hours) + ":" + (t2Minutes < 10 ? "0" + t2Minutes : t2Minutes)
            + ":" + (t2Seconds < 10 ? "0" + t2Seconds : t2Seconds);
        this.timeDialog = false;
    }

    public saveAll() {
        let arr: Array<IRoomSortModel> = [];
        for (let i = 0; i < this.sortList.length; i++) {
            let result = this.sortList[i];
            result.weeks.forEach(value => {
                let mod: IRoomSortModel = {
                    baseroomId: result.baseroomId,
                    baseroomName: result.baseroomName,
                    roomId: value.roomId,
                    roomName: value.roomName,
                    week: value.weekName,
                    begintime: result.begintime,
                    endtime: result.endtime,
                }
                //同一个基础诊室不能同一时间有不同的配置
                let fArr = arr.filter(v => {
                    return v.baseroomId == mod.baseroomId && (v.begintime == mod.begintime&&v.endtime==mod.endtime)&&v.week==mod.week
                });
                if (fArr.length <= 0) {
                    arr.push(mod)
                }
            })
        }
        console.error("所有数据:", arr);
        RoomSortModule.insertBatchRoomSort(arr).then((value: any) => {
            console.error(value);
            if (value > 0) {
                this.srcList = arr;
                this.updateShowList(arr);
            }
        });
    }

    created() {
        this.init()
    }

    public getList() {
        return this.allList;
    }
    public getFields() {
        return "title,staffName,jobCategory"
    }

    public setShowList() {
        let startIndex = this.pageSize * (this.currentPage - 1);
        this.list = this.allList.filter((value, index) => {
            return index >= startIndex && index < startIndex + this.pageSize;
        });
    }


    public onAdd() {
        //this.handleClick(TouchType.ADD, null);
    }

    public onRefresh() {
        console.error("onClick onRefresh");
        this.isShow = true;
    }

    public onSearch(val: any) {
        this.list = val;
    }

    public async init() {
        //1.获取所有的科室信息
        let result: any = await DeptsModule.getDepts();
        console.error(result)

        let depts: any = {};//dept: object, children: []
        for (let i = 0; i < result.length; i++) {
            if (!result[i].parentCode || result[i].parentCode == '-') {
                depts[result[i].deptCode] = { dept: result[i], deptName: result[i].deptName, children: [] }
            }
        }
        for (let i = 0; i < result.length; i++) {
            if (result[i].parentCode) {
                if (!depts[result[i].parentCode]) {
                    depts[result[i].deptCode] = { dept: result[i], deptName: result[i].deptName, children: [] }
                } else {
                    depts[result[i].parentCode].children.push({ dept: result[i], deptName: result[i].deptName, children: [] });
                }
            }
        }
        let arr: any = [];
        for (let key in depts) {
            arr.push(depts[key]);
        }
        this.deptData = arr;
    }

    public handleSizeChange(val: number) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.setShowList();
    }
    public handleCurrentChange(val: number) {
        console.log(`当前页: ${val}`);
        this.currentPage = val;
        this.setShowList();
    }

    public onDelete(row: any) {
        console.error(row);
        let ids: Array<number> = [];
        let boo = this.srcList.some(value => {
            return value.sortId == row.sortId;
        })
        if (!boo) {
            return;
        }
        row.weeks.forEach((element: IWeekModel) => {
            ids.push(element.sortId);
        });
        RoomSortModule.deleteRoomSortOne(ids).then((v: any) => {
            console.error(v);
            if (v > 0) {
                this.sortList = this.sortList.filter(value => {
                    return ids.indexOf(value.sortId) == -1;
                });
            }
        });
    }

}
</script>


<style>
.sort-root {
    width: 100%;
    height: calc(100vh - 200px);
    display: flex;
    flex-direction: row;
    flex: 1;
}

.sort-left {
    width: 200px;
    height: 100%;
    background-color: #FFF;
    /* margin-right: 10px; */
    /* overflow-y: auto;
    overflow-x: hidden; */
}

.sort-right {
    flex: 1;
    /* width: 100%; */
    height: 100%;
    /* background-color: red; */
    display: flex;
    flex-direction: column;
}

.treeDiv {
    overflow-y: auto;
    height: 100%;
}

.right-header {
    height: 60px;
    width: 100%;
}

.right-main {
    flex: 1;
    width: 100%;
}

.right-main .el-date-editor.el-input {
    width: 110px;
}

.right-footer {
    flex: 1;
}
</style>